package www.openteam.com.api;

import android.content.res.Resources;
import android.support.annotation.NonNull;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.CacheControl;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import www.openteam.com.OTApplication;
import www.openteam.com.R;
import www.openteam.com.bean.InsertStatus;
import www.openteam.com.network.exception.CustomizeException;
import www.openteam.com.service.DownloadService;
import www.openteam.com.tool.FileTools;
import www.openteam.com.tool.NetworkUtil;
import www.openteam.com.tool.SpUtils;

/**
 * Created by kylin on 2016/12/14.
 */

public class HttpManager {

    private static OkHttpClient client;
    private static HttpApiService httpApiService;
    private static HttpApiService.HZRB hzrb_httpApiService;
    private static HttpApiService.BaseWorkOrder base_httpApiService;
    private static HttpApiService.ZZWorkorder zz_httpApiService;
    private static Retrofit retrofit;
    private static Resources res = OTApplication.getmContext().getResources();
    //url
//    private static final String ENDPOINT = res.getString(R.string.endPoint_n);
//    private static final String ENDPOINT = " http://192.168.1.119:8090/index.php/OpenTeam/";
    public static final String ENDPOINT = "http://sz-openteam.iask.in:16371/index.php/OpenTeam/";
//    public static final String ENDPOINT = "http://192.168.131.241:8090/index.php/OpenTeam/";//HZ_RB
//    public static final String ENDPOINT = "http://192.168.1.7:8090/index.php/OpenTeam/";//ZZ
//    private static final String ENDPOINT = "http://192.168.1.223:8090/index.php/OpenTeam/";
//private static final String ENDPOINT = " http://61.143.108.122:8090/index.php/OpenTeam/";
//    private static final String ENDPOINT = " http://192.168.0.101:5001/index.php/OpenTeam/";
//    private static final String ENDPOINT = " http://192.168.1.22:8090/index.php/OpenTeam/";

    /**
     * @return 返实例化的Api
     */
    public static HttpApiService getHttpApiService() {
        if (httpApiService == null) {
            httpApiService = getRetrofit().create(HttpApiService.class);
        }

        return httpApiService;
    }

    public static HttpApiService.HZRB getHttpHZRBApiService() {
        if (hzrb_httpApiService == null) {
            hzrb_httpApiService = getRetrofit().create(HttpApiService.HZRB.class);
        }

        return hzrb_httpApiService;
    }

    public static HttpApiService.BaseWorkOrder getHttpBaseApiService() {
        if (base_httpApiService == null) {
            base_httpApiService = getRetrofit().create(HttpApiService.BaseWorkOrder.class);
        }

        return base_httpApiService;
    }

    public static HttpApiService.ZZWorkorder getHttpZZApiService() {
        if (zz_httpApiService == null) {
            zz_httpApiService = getRetrofit().create(HttpApiService.ZZWorkorder.class);
        }

        return zz_httpApiService;
    }
    /**
     * 实例化Retrofit
     *
     * @return 实例化Retrofit
     */
    public static Retrofit getRetrofit() {
        if (retrofit == null) {
            synchronized (HttpManager.class) {
                if (retrofit == null) {
                    //添加一个拦截器,打印所有log
                    HttpLoggingInterceptor httpLoggingInterceptor = new
                            HttpLoggingInterceptor();

                    httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

                    //设置 请求缓存的大小和位置
//                    File cacheFile = new File(OTApplication.getmContext().getCacheDir(),
//                            "cache");
//                    Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);//设置缓存大小为50M

                    client = new OkHttpClient
                            .Builder()
                            .addInterceptor(httpLoggingInterceptor)
                            .connectTimeout(601, TimeUnit.SECONDS)
                            .readTimeout(601, TimeUnit.SECONDS)
                            .writeTimeout(601, TimeUnit.SECONDS)
                            .build();


                    // 获取retrofit的实例
                    retrofit = new Retrofit
                            .Builder()
                            .baseUrl(ENDPOINT)  //自己配置
                            .client(client)
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                            .addConverterFactory(GsonConverterFactory.create()) //这里是用的fastjson的
                            .build();
                }
            }

        }
        return retrofit;
    }


    private static Interceptor addQueryParameterInterceptor() {

        Interceptor addQueryParamterInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
                Request request;
                HttpUrl modifiedUrl = originalRequest.url().newBuilder()
                        .addQueryParameter("op", "")
                        .build();

                request = originalRequest.newBuilder().url(modifiedUrl)
                        .build();
                return chain.proceed(request);
            }
        };
        return addQueryParamterInterceptor;
    }

    private static Interceptor addHeaderInterceptor() {
        Interceptor headerInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
                Request.Builder requestBuilder = originalRequest.newBuilder()
                        // Provide your custom header here
                        .header("token", (String) SpUtils.get("token", ""))
                        .method(originalRequest.method(), originalRequest.body());
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        };

        return headerInterceptor;
    }

    /**
     * 设置缓存
     */

    private static Interceptor addCacheInterceptor() {
        Interceptor cacheInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (!NetworkUtil.isNetworkAvailable(OTApplication.getmContext())) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                }

                Response response = chain.proceed(request);
                if (NetworkUtil.isNetworkAvailable(OTApplication.getmContext())) {
                    int maxAge = 0;
                    response.newBuilder()
                            .header("Cache-Control", "public, max-age=" + maxAge)
                            .removeHeader("Retrofit")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                            .build();
                } else {
                    //无网络时,设置超时为4周, 只对get有用, post 没有缓冲
                    int maxStale = 60 * 60 * 24 * 28;
                    response.newBuilder()
                            .header("Cache-Control", "public, only-if-cached, max-stale=" +
                                    maxStale)
                            .removeHeader("nyn")
                            .build();
                }
                return response;
            }
        };
        return cacheInterceptor;
    }

}
